package com.lancoo.znbkxx.teacher.ui.fragment

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.tu.loadingdialog.LoadingDailog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.appbar.AppBarLayout
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSID
import com.lancoo.znbkxx.teacher.Ext.Companion.GLOBAL_GRADE
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.PaperListAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPreview.AibkPaperPreviewActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.base.SharedPreferencesHelper
import com.lancoo.znbkxx.teacher.databinding.FmtBasicReviewBinding
import com.lancoo.znbkxx.teacher.model.OperationHelp
import com.lancoo.znbkxx.teacher.model.data.ClassFlag
import com.lancoo.znbkxx.teacher.model.data.PaperSetSection
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.prolificinteractive.materialcalendarview.CalendarDay
import com.prolificinteractive.materialcalendarview.MaterialCalendarView
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener

import paperToChaKanChengJi.CheckScoreActivity

/**
 * @author : Admin
 * @date   : 2019/7/26 10:50
 * @desc   :
 */
class BasicReviewFragment : BaseVMFragment<PaperViewModel, FmtBasicReviewBinding>(),
        BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener,
        View.OnClickListener, OnDateSelectedListener {
    private lateinit var adapter: PaperListAdapter
    private val list = mutableListOf<PaperSetSection>()
    private val classFlagList = mutableListOf<ClassFlag>()
    private val layer by lazy { arguments?.getInt("layer") }
    private val dialog by lazy {
        CalendarDialog(classFlagList).apply {
            setStyle(
                    DialogFragment.STYLE_NORMAL,
                    R.style.Theme_dialog
            )
        }
    }
    private val editDialog by lazy {
        DateEditDialog().apply {
            setStyle(
                    DialogFragment.STYLE_NORMAL,
                    R.style.Theme_dialog
            )
        }
    }
    val lists = mutableListOf<CalendarDay>()
    var position: Int = 0
    private lateinit var headView: View
    private val loadingDialog by lazy {
        LoadingDailog.Builder(context).setMessage("发布中...").setCancelOutside(false)
                .setCancelable(false).create()
    }
    private val editLoadingDialog by lazy {
        LoadingDailog.Builder(context).setMessage("修改中...").setCancelOutside(false)
                .setCancelable(false).create()
    }

    companion object {
        private const val LAYER = "layer"
        fun newInstance(layer: Int): BasicReviewFragment {
            val fragment = BasicReviewFragment()
            val bundle = Bundle()
            bundle.putInt(LAYER, layer)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun providerContext(): Any? {
        return this
    }

    override fun providerVMClass(): Class<PaperViewModel>? {
        return PaperViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_basic_review
    }

    override fun initView() {
        viewModel.pageNo.value = 1
        viewModel.pageSize.value = 5
        val lm = LinearLayoutManager(requireContext()).apply { orientation = RecyclerView.VERTICAL }
        adapter = PaperListAdapter(R.layout.item_paper_head, list)
        adapter.onItemChildClickListener = this
        adapter.onItemClickListener = this
        adapter.setEnableLoadMore(true)
        adapter.openLoadAnimation()
        adapter.setOnLoadMoreListener({
            if (viewModel.mPaperList.value!!.Count >= viewModel.pageSize.value!!) {
                viewModel.pageSize.value = viewModel.pageSize.value!! + 5
                initPaper()
            } else {
                adapter.loadMoreEnd()
            }
        }, binding.rv)
        binding.swipeLayout.setOnRefreshListener {
            Handler().post {
                viewModel.pageNo.value = 1
                viewModel.pageSize.value = 5
                initPaper()
            }
        }
        binding.rv.layoutManager = lm
        headView = when (layer) {
            0 -> layoutInflater.inflate(R.layout.item_header_basic, null)
            1 -> layoutInflater.inflate(R.layout.item_header_review, null)
            2 -> layoutInflater.inflate(R.layout.item_header_emu, null)
            3 -> layoutInflater.inflate(R.layout.item_header_textbook, null)
            4 -> layoutInflater.inflate(R.layout.item_header_topic, null)
            else -> layoutInflater.inflate(R.layout.item_header_basic, null)
        }
        headView.findViewById<TextView>(R.id.tv_main).apply {
            typeface = Typeface.createFromAsset(requireContext().assets, "fonts/cool_black.TTF")
        }
        headView.findViewById<TextView>(R.id.tv_sub).apply {
            typeface = Typeface.createFromAsset(requireContext().assets, "fonts/cool_black.TTF")
        }
        headView.findViewById<TextView>(R.id.tv_child).apply {
            typeface = Typeface.createFromAsset(requireContext().assets, "fonts/cool_black.TTF")
        }
        adapter.addHeaderView(headView)
        binding.rv.adapter = adapter
    }

    fun initPaper() {
        layer?.let {
            viewModel.getPaperSetListForMobile(
                    CurrentUser.getUserID(),
                    CurrentUser.getToken(),
                    CurrentUser.getSchoolID(),
                    COURSE_CLASSID,
                    layer!!,
                    viewModel.pageNo.value!!,
                    viewModel.pageSize.value!!
            )
        }
    }

    override fun startObserve() {
        viewModel.mPaperList.observe(this, Observer {
            list.clear()
            val mAppBarChildAt = when (layer) {
                0, 1, 2 -> (parentFragment as PaperFollowingFragment).binding.appBar.getChildAt(0)
                else -> (parentFragment as CommonReviewFragment).binding.appBar.getChildAt(0)
            }

            val mAppBarParams = mAppBarChildAt.layoutParams as AppBarLayout.LayoutParams
            val isAgreePermissions = SharedPreferencesHelper.getBoolean("isAgreePermissions", false)
            if (it.List.isNullOrEmpty() || !isAgreePermissions) {
                binding.ivEmpty.visibility = View.VISIBLE
                adapter.setNewData(null)
            } else {
                binding.ivEmpty.visibility = View.GONE
                mAppBarParams.scrollFlags =
                        AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
                mAppBarChildAt.layoutParams = mAppBarParams
                it.List.forEach { paperSet ->
                    if (paperSet.PaperList.size > 0) {
                        val sectionHeader = PaperSetSection(true, "", paperSet,
                                paperSet.PaperList[0].Layer)
                        list.add(sectionHeader)
                        paperSet.PaperList.forEach { paper ->
                            val section = PaperSetSection(paper)
                            list.add(section)
                        }
                    }
                }
                adapter.setNewData(list)
            }
            binding.swipeLayout.finishRefresh()
            adapter.setEnableLoadMore(true)
            adapter.loadMoreComplete()
        })
        viewModel.success.observe(this, Observer {
            loadingDialog.dismiss()
            if (it.ReleaseResult) {
                dialog.dismiss()
                MyToast.showToast( "发布成功")
                OperationHelp.operationLog(1, activity)
                initPaper()
            } else {
                MyToast.showToast( "发布失败")
            }
        })
        viewModel.mEditDurationInfo.observe(this, Observer {
            editLoadingDialog.dismiss()
            when (it) {
                false -> {
                    MyToast.showToast( "试卷已到期，无法修改作答期限")
                }
                true -> {
                    MyToast.showToast( "修改成功")
                    editDialog.dismiss()
                    initPaper()
                }
            }
        })
        viewModel.mSubmittedInfo.observe(this, Observer {
            val reviewedDialog = ReviewedDialog.newInstance(null, it).apply {
                setStyle(
                        DialogFragment.STYLE_NORMAL,
                        R.style.Theme_dialog
                )
            }
            reviewedDialog.show(parentFragmentManager, "reviewedDialog")
        })
        viewModel.mClassFlag.observe(this, Observer {
            classFlagList.clear()
            classFlagList.addAll(it)
            dialog.clickListener = this
            dialog.selectedListener = this
            dialog.text = "请选择发布日期"
            dialog.show(parentFragmentManager, "calendar")
        })
        viewModel.mErrorMsg.observe(this, Observer {
            loadingDialog.dismiss()
            editLoadingDialog.dismiss()
            MyToast.showToast( it)
        })
    }


    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val setId = list[position].t.SetID
        val paperId = list[position].t.PaperID
        val paperName = list[position].t.PaperName
        val intent = Intent()
        intent.putExtra("setId", setId)
        intent.putExtra("paperId", paperId)
        intent.putExtra("layer", layer)
        when (view?.id) {
            R.id.tv_detail -> {
                if (list[position].t.State == 2) {
                    return
                }
                intent.putExtra("paperName", paperName)
//                intent.setClass(requireActivity(), ChaKanChengJiActivity::class.java)
                intent.setClass(requireActivity(), CheckScoreActivity::class.java)
                startActivity(intent)
            }
            R.id.tv_comment -> {
                if (list[position].t.EvalCount == 0) {
                    return
                }
//                intent.setClass(requireActivity(), PingYueShiJuanActivity::class.java)
//                startActivity(intent)
                AibkQuesMarkActivity.launch(requireActivity(), setId, "", paperId, paperName, false)
            }
            R.id.tv_publish -> {
                this.position = position
                viewModel.getGradeClassWithPaperState(
                        GLOBAL_GRADE,
                        CurrentUser.getSchoolID(),
                        setId,
                        paperId,
                        CurrentUser.getToken(),
                        CurrentUser.getUserID()
                )
            }
            R.id.tv_time -> {
                this.position = position
                val item = adapter?.getViewByPosition(
                        binding.rv,
                        position + adapter.headerLayoutCount,
                        R.id.tv_time
                ) as TextView
                editDialog.clickListener = this
                editDialog.answerTime = "当前作答期限：${item.text}"
                editDialog.startTime = item.text.split("~")[0].replace(".", "-")
                editDialog.endTime = item.text.split("~")[1].replace(".", "-")
                parentFragmentManager.let { editDialog.show(it, "editDialog") }
            }
            R.id.textView18, R.id.tv_total, R.id.tv_finished -> viewModel.getStuProgress(
                    paperId,
                    COURSE_CLASSID,
                    CurrentUser.getSchoolID(),
                    CurrentUser.getToken(),
                    CurrentUser.getUserID()
            )
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val setId = list[position].t.SetID
        val paperId = list[position].t.PaperID
//        val intent = Intent()
//        intent.putExtra("setId", setId)
//        intent.putExtra("paperId", paperId)
//        intent.putExtra("layer", layer)
//        intent.setClass(requireActivity(), AibkPreviewPaperActivity::class.java)
//        startActivity(intent)
        AibkPaperPreviewActivity.launch(requireActivity(), paperId,setId, false)
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.btn_cancel -> dialog.dismiss()
            R.id.btn_publish -> {
                release(position)
            }
            R.id.tv_confirm -> {
                editLoadingDialog.show()
                viewModel.setPaperAnswerDuration(
                        list[position].t.PaperID,
                        COURSE_CLASSID,
                        "${editDialog.binding.tvStarttime.text} 00:00:00",
                        "${editDialog.binding.tvEndtime.text} 23:59:59",
                        CurrentUser.getToken(),
                        CurrentUser.getSchoolID(),
                        list[position].t.SetID,
                        GLOBAL_GRADE,
                        CurrentUser.getUserID()
                )
            }
        }
    }

    override fun onDateSelected(
            widget: MaterialCalendarView,
            date: CalendarDay,
            selected: Boolean
    ) {
        lists.addAll(widget.selectedDates)
    }

    private fun release(position: Int) {
        val state = list[position].t.State
        val setId = list[position].t.SetID
        val paperId = list[position].t.PaperID
        val paperList = mutableListOf<String>()
        paperList.add(paperId)
        val startTime: String
        val endTime: String
        val startMonth: String
        val startDay: String
        val endMonth: String
        val endDay: String
        dialog.widget.selectedDates.let {
            if (it.isEmpty()) {
                MyToast.showToast("请选择发布日期")
                return
            }
            startMonth = if (it[0].month < 10) "0${it[0].month}" else "${it[0].month}"
            startDay = if (it[0].day < 10) "0${it[0].day}" else "${it[0].day}"
            endMonth =
                    if (it[it.size - 1].month < 10) "0${it[it.size - 1].month}" else "${it[it.size - 1].month}"
            endDay =
                    if (it[it.size - 1].day < 10) "0${it[it.size - 1].day}" else "${it[it.size - 1].day}"
            startTime = "${it[0].year}-$startMonth-$startDay 00:00:00"
            endTime = "${it[it.size - 1].year}-$endMonth-$endDay 23:59:59"
        }
        val classList = classFlagList.filter { it.checked }
        if (classList.isNullOrEmpty()) {
            MyToast.showToast( "请选择发布班级")
            return
        }
        loadingDialog.show()
//        classList.forEach {
//            it.Layer = layer!!
//            it.SetID = setId
//            it.state = state
//        }
//        viewModel.releaseAuditPaper(
//                list[position].t.SetID,
//                GLOBAL_GRADE,
//                CurrentUser.Token,
//                paperList,
//                startTime,
//                endTime,
//                classList.toMutableList(),
//                CurrentUser.UserID,
//                CurrentUser.SchoolID,
//                layer!!
//        )
    }

    override fun onStart() {
        super.onStart()
        initPaper()
    }
}